import 'package:flutter/material.dart';
import 'package:flutter_douban/config/Http_service.dart';
import 'package:flutter_douban/config/app_colors.dart';
import 'package:flutter_douban/loading/custom_footer.dart';
import 'package:flutter_douban/loading/custom_header.dart';
import 'package:flutter_douban/main_page/home/notes/note_detail_footer.dart';
import 'package:flutter_douban/model/active_big_model.dart';
import 'package:flutter_douban/model/note_model.dart';
import 'package:flutter_douban/tool_views/loading_page.dart';
import 'package:flutter_douban/tool_views/stance_page.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'home_card_view.dart';
import 'note_detail_centerView.dart';
import 'note_detail_header.dart';
import 'note_detail_headerView.dart';

class NoteDetailPage extends StatefulWidget {
  final int id;
  const NoteDetailPage({Key? key, required this.id}) : super(key: key);

  @override
  _NoteDetailPageState createState() => _NoteDetailPageState();
}

class _NoteDetailPageState extends State<NoteDetailPage> {
  @override

  /// 下拉刷新控制器
  late EasyRefreshController _easyRefreshController;

  /// 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController? _scrollController;
  late NoteModel _model;

  /// 列表数组模型
  List<ActiveBigModel> _relatedList = ActiveBigModelList([]).list;
  int page = 0;
  int limit = 10;
  bool hasMore = true;
  bool loading = true;
  bool error = false;
  String? errorMsg;

  /// 获取详情内容
  Future _getNotesContentData() async {
    try {
      /// 全部数据
      Map<String, dynamic> result =
          await HttpService.getNotesContentData(id: widget.id);

      /// 列表
      NoteModel model = NoteModel.fromJson(result['note']);
      setState(() {
        _model = model;
        _onRefresh();

      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  /// 获取相关笔记数据
  Future _getRelatedNotesData({bool replace = true}) async {
    try {
      /// 全部数据
      Map<String, dynamic> result = await HttpService.getNotesDetailData(
          page: page, pageSize: 10, id: widget.id);

      /// 列表
      ActiveBigModelList activeBigModelList =
          ActiveBigModelList.fromJson(result['list']);
      setState(() {
        page++;
        if (replace) {
          _relatedList = activeBigModelList.list;
        } else {}
      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _easyRefreshController = EasyRefreshController();
    _scrollController = ScrollController();
    _getNotesContentData();
  }

  @override
  void dispose() {
    _easyRefreshController.dispose();
    _scrollController!.dispose();
    super.dispose();
  }

  // 刷新回调(null为不开启刷新)
  Future _onRefresh() async {
    if (error) {
      setState(() => error = false);
    }
    page = 0;
    await _getRelatedNotesData();
    // 恢复刷新状态 使onLoad再次可用
    _easyRefreshController.resetLoadState();
  }

  // 加载回调(null为不开启加载)
  Future _onLoad() async {
    if (hasMore) {
      await _getRelatedNotesData(replace: false);
    }
    // 结束加载
    _easyRefreshController.finishLoad(noMore: !hasMore);
  }

  Widget build(BuildContext context) {
    return Scaffold(
      body: (_relatedList.length > 0) ? Container(
        color: AppColors.white,
        child: Stack(
          children: [
            Container(
              padding: EdgeInsets.only(
                top: kToolbarHeight + 8,
                bottom: kToolbarHeight,
              ),
              child: EasyRefresh(
                  firstRefresh: false,
                  firstRefreshWidget: LoadingPage(),
                  header: CustomHeaderView(),
                  footer: CustomFooterView(),
                  controller: _easyRefreshController,
                  enableControlFinishRefresh: false,
                  enableControlFinishLoad: true,
                  // onRefresh: _onRefresh,
                  onLoad: _onLoad,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      DetailHeaderView(model: _model),
                      NoteCenterView(
                        model: _model,
                      ),
                      Container(
                        padding: EdgeInsets.only(left: 15,right: 15),
                        color: Colors.white,
                        width: MediaQuery.of(context).size.width,
                        child: Text(
                          '相关笔记',
                          style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 18,
                              color: Colors.black),
                        ),
                      ),
                      _gradWidget(),
                    ],
                  )),
            ),
            Positioned(
              top: 0,
              child: NoteDetailHeader(model: _model,),
            ),
            Positioned(
              bottom: 0,
              child: SafeArea(
                child: NoteDetailFooter(model: _model),
              ),
            )
          ],
        ),
      ) : StancePage(),
    );
  }

  /// 瀑布流
  Widget _gradWidget() {
    return Container(
      padding: EdgeInsets.only(
        left: 5,
        right: 5,
      ),
      color: Colors.white,
      child: StaggeredGridView.countBuilder(
        controller: _scrollController,
        itemCount: _relatedList.length,
        primary: false,
        shrinkWrap: true,
        crossAxisCount: 4,
        mainAxisSpacing: 10.0,
        crossAxisSpacing: 5.0,
        itemBuilder: (context, index) => ActiveCardView(
          model: _relatedList[index],
        ),
        staggeredTileBuilder: (index) => StaggeredTile.fit(2),
      ),
    );
  }
}
